package com.czjk.service.impl;


import com.czjk.entity.PageResult;
import com.czjk.mapper.CheckGroupMapper;
import com.czjk.mapper.SetMealAndCheckgroupMapper;
import com.czjk.mapper.SetMealMapper;
import com.czjk.pojo.CheckGroup;
import com.czjk.pojo.Setmeal;
import com.czjk.service.SetMealService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 */
@Service
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealMapper setMealMapper;
    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Autowired
    private SetMealAndCheckgroupMapper setMealAndCheckgroupMapper;

    @Override
    public PageResult findByPage(Integer currentPage, Integer pageSize, String queryString) {
        //1 设置分页参数
        PageHelper.startPage(currentPage,pageSize);
        //2 带条件分页查询
        Page page=(Page)setMealMapper.findAll(queryString);
        //3 封装分页结果并返回
        return new PageResult(page.getTotal(),page.getResult());
    }

    //添加套餐
    @Transactional
    @Override
    public void add(Setmeal setmeal, Integer[] ids) {
        //添加套餐
        setMealMapper.add(setmeal);
        //向关系表中添加数据(操作中间表t_setmeal_checkgroup)，思考：此处需要套餐id，如何拿到？
        if(ids!=null && ids.length>0){
            for (Integer checkGroupId : ids) {
                setMealAndCheckgroupMapper.addSetmealAndCheckGroup(setmeal.getId(),checkGroupId);
            }
        }
    }

    //根据id查询套餐
    @Override
    public Setmeal findById(Integer id) {
        return setMealMapper.findById(id);
    }

    @Transactional
    //根据id查询检查组
    @Override
    public List<CheckGroup> findCheckGroupById(Integer id) {
        return checkGroupMapper.findCheckGroupsByCheckGroupId(id);

    }

    //更新套餐
    @Transactional
    @Override
    public void update(Setmeal setmeal, Integer[] ids) {
        //更新套餐信息
        setMealMapper.update(setmeal);
        //更新套餐和检查组的关联关系(多对多)(先删除关联关系，再添加关联关系)
        if(ids!=null && ids.length>0){
            //先删除关联关系(操作中间表t_setmeal_checkgroup)
            setMealAndCheckgroupMapper.deleteSetmealAndCheckGroup(setmeal.getId());
            //再添加关联关系(操作中间表t_setmeal_checkgroup)
            for (Integer checkGroupId : ids) {
                setMealAndCheckgroupMapper.addSetmealAndCheckGroup(setmeal.getId(),checkGroupId);
            }
        }
    }

    //删除套餐
    @Transactional
    @Override
    public void delete(Integer id) {
        //先删除套餐和检查组的关联关系(操作中间表t_checkgroup_checkitem)
        setMealAndCheckgroupMapper.deleteSetmealAndCheckGroup(id);
        //再删除套餐信息
        setMealMapper.delete(id);
    }
}